package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.entity.YddCate;
import com.itheima.youdianda.service.YddCateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/ydd_cate")
public class YddCateController {
    @Autowired
    private YddCateService yddCateService;


    @GetMapping("/list")
    public R<Page> page(String catename, int page, int limit){
        log.info("catename={},page={},limit={}",catename,page,limit);

        //创建分页构造器对象
        Page<YddCate> pageInfo = new Page<>(page,limit);

        //构造条件构造器
        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(catename!=null,YddCate::getCatename,catename);

        //添加排序条件
        queryWrapper.orderByDesc(YddCate::getId);

        //执行分页查询
        Page<YddCate> res = yddCateService.page(pageInfo,queryWrapper);
        return R.success(res);
    }


    /**
     * 查询分类类型
     * @return
     */
    @GetMapping("/all")
    public R<List<YddCate>> page(){
        log.info("收到浏览器的查询分类类型请求");

//        //创建分页构造器对象
//        Page<YddCate> pageInfo = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();


        //添加排序条件
        queryWrapper.orderByDesc(YddCate::getId);

        //执行分页查询
        List<YddCate> res = yddCateService.list(queryWrapper);
        return R.success(res);
    }


    /**
     * 添加分类
     * @param yddCate
     * @return
     */
    @PostMapping("/add")
    public R<String> save (@RequestBody YddCate yddCate){
        log.info("添加分类YddCate:{}",yddCate);
        yddCateService.save(yddCate);
        return R.success("添加分类成功");
    }


    /**
     * 修改分类信息
     * @param yddCate
     * @return
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody YddCate yddCate){
        log.info("修改分类信息YddCate:{}",yddCate);
        yddCateService.updateById(yddCate);
        return R.success("修改分类成功");
    }


    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping("/del")
    public R<String> delete(Long id){
        log.info("删除分类，id为:{}",id);
        yddCateService.removeById(id);
        return R.success("删除分类信息成功");
    }


    /**
     * 根据Id查询分类详情
     * @param yddCate
     * @return
     */
    @GetMapping("/rowInfo")
    public R<List<YddCate>> list(YddCate yddCate){
        //构造查询条件
        LambdaQueryWrapper<YddCate> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(yddCate.getId()!=null,YddCate::getId,yddCate.getId());

        List<YddCate> list =yddCateService.list(queryWrapper);
        return R.success(list);
    }
}
